#!/bin/ksh -p

usage () {
    echo "$0 [options]"
    echo "   -h, --help     Display this help"
    echo "   -a display     Add a new Sun Ray display"
    echo "   -d display     Delete a Sun Ray display"
    echo "   -l             List all Sun Ray displays"
    exit 1
}

AWK="/usr/gnu/bin/awk"
SED="/usr/gnu/bin/sed"
SEAT_TOOL="/usr/sbin/ck-seat-tool"
LIST_TOOL="/usr/bin/ck-list-sessions"
HIST_TOOL="/usr/bin/ck-history"

optype=""
oparg=""

for i in "$@"
do
  if [ ! "x$optype" = "x" ]; then
    oparg=$i
    break
  fi
  if [ "x$i" = "x-h" -o "x$i" = "x--help" ]; then
    break
  fi
  if [ "x$i" = "x-a" ]; then
    optype="add"
    continue
  fi
  if [ "x$i" = "x-d" ]; then
    optype="delete"
    continue
  fi
  if [ "x$i" = "x-l" ]; then
    optype="list"
    break
  fi
done

case $optype in
  add)
# gdmdynamic -a 10=/usr/X11/bin/Xorg
    oparg=`echo $oparg | awk -F\= '{print $1}'`
    seatid=`$HIST_TOOL --last | $AWK -v disp=":$oparg" '{if ($6 == disp) print $N0}' | head -1 | $AWK '{print $4}'`
    if [ "x$seatid" = x ]; then
      seatid="SunraySeat$oparg"
    fi
    $SEAT_TOOL -a --display-type=Sunray --seat-id=$seatid display=:$oparg
    ;;
  delete)
# gdmdynamic -d 10
    ssid=`$LIST_TOOL -f session-id,x11-display,display-type | grep Sunray | $SED -e s/\'//g | $AWK -v disp=:$oparg '{if ($2 == disp) print $1}'`
    if [ ! "x$ssid" = "x" ]; then
      $SEAT_TOOL -d --session-id=$ssid
    fi
    ;;
  list)
# gdmdynamic -l
    sessions=`$LIST_TOOL -f session-id,x11-display,display-type | grep Sunray | $AWK '{print $2}' | $SED -e s/\'//g`
    dyps=""
    for i in $sessions
    do
      if [ ! "x$i" = "x" ]; then
         dyps="$i;$dyps"
      fi
    done
    echo $dyps
    ;;
  * )
    usage
    ;;
esac
